package com.wisdom.smartbook.activity;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.wisdom.smartbook.R;
import com.wisdom.smartbook.base.BaseActivity;
import com.wisdom.smartbook.utils.DialogUtil;
import com.wisdom.smartbook.utils.KLog;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * 主页
 */
public class PdfBrowserActivity extends BaseActivity {

    public String urtStr = "";//学生
    private WebView mWebView;
    private FrameLayout mRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    protected int getLayoutId() {

        return R.layout.activity_main;

    }

    protected void initView() {
        urtStr = getIntent().getStringExtra("urlStr");
        initWebView();
        setWeb();
    }

    @Override
    protected void initData() {
        DialogUtil.showProgressDialog(this, "正在加载...");
        mWebView.loadUrl("file:///android_asset/index.html?" + urtStr);
        mHandler.sendEmptyMessageDelayed(1, 15000);
    }




    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1 || msg.what == 12) {
                DialogUtil.closeProgressDialog();
            }
        }
    };

    private void setWeb() {
        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = mWebView.getSettings().getClass();
                Method method = clazz.getMethod(
                        "setAllowUniversalAccessFromFileURLs", boolean.class);//利用反射机制去修改设置对象
                if (method != null) {
                    method.invoke(mWebView.getSettings(), true);//修改设置
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void initWebView() {
        mRootView = findViewById(R.id.root_view);
        mWebView = findViewById(R.id.main_webview);
        //开启webView硬件加速
        this.mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        final WebSettings webSetting = mWebView.getSettings();
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        if (mWebView.getSettingsExtension() != null) {
            mWebView.getSettingsExtension().setDisplayCutoutEnable(true);
        }
        webSetting.setAllowFileAccess(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setBlockNetworkImage(true);
        webSetting.setNeedInitialFocus(false);
        //自适应屏幕
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.setDrawingCacheEnabled(true);
        webSetting.setLoadWithOverviewMode(true);
//        //修改相应设置即可
        webSetting.setMediaPlaybackRequiresUserGesture(false);
        webSetting.setAppCachePath(mActivity.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(mActivity.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(mActivity.getDir("geolocation", 0)
                .getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);


        long time = System.currentTimeMillis();
        removeSearchBoxImpl();
        CookieSyncManager.createInstance(mActivity);
        CookieSyncManager.getInstance().sync();
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webSetting.setBlockNetworkImage(false);
                mWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, String s) {
                KLog.d("shouldInterceptRequest", s);
                return super.shouldInterceptRequest(webView, s);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                KLog.d("shouldOverrideUrlLoading", url);

                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                KLog.e("shouldOverrideUrlLoading2", webResourceRequest.getUrl().toString());
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
//                super.onReceivedSslError(webView, sslErrorHandler, sslError);
                sslErrorHandler.proceed();
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                KLog.d(i, s, s);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
                                        @Override
                                        public void onProgressChanged(WebView view, int newProgress) {
                                            super.onProgressChanged(view, newProgress);
                                            KLog.e("加载进度", newProgress + "");
                                        }

                                        @Override
                                        public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                                            return super.onJsAlert(webView, s, s1, jsResult);
                                        }
                                    }
        );
    }

    @Override
    protected void onPause() {
        mWebView.onPause();
        mWebView.pauseTimers();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mWebView.onResume();
        mWebView.resumeTimers();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeSessionCookies(null);
        cookieManager.removeAllCookie();
        cookieManager.flush();
        mRootView.removeAllViews();
        if (mWebView != null) {
            mWebView.clearCache(false);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }

    }

    private boolean removeSearchBoxImpl() {
        if (hasHoneycomb() && !hasJellyBeanMR1()) {
            mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
            mWebView.removeJavascriptInterface("accessibility");
            mWebView.removeJavascriptInterface("accessibilityTraversal");
            return true;
        }
        return false;
    }

    private boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    private boolean hasJellyBeanMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
    }


    /**
     * 设置点击返回按钮，跳转到上一个html页面，而不是退出当前activity
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();

            }
            return true;

        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }


}